//
//  JHUHospital.m
//  iHealthEHR
//
//  Created by Joseph Ayo Akinyele on 3/29/10.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "JHUHospital.h"

/*@interface NSURLRequest (IgnoreSSL)
// to ignore unsigned SSL certs
+(BOOL) allowsAnyHTTPSCertificateForHost:(NSString *) host;
@end

@implementation NSURLRequest (IgnoreSSL)

+(BOOL) allowsAnyHTTPSCertificateForHost:(NSString *)host
{
	NSLog(@"URL Suffix: %@", host);
	return YES;
}
@end */




@implementation JHUHospital
@synthesize xmlData, privateKey;
@synthesize dataLink;
@synthesize ccrEntries;

-(id) init
{
	// set super-class init to ourself
	if(self = [super init]) {
		// do initialization of data items
		//xmlData = [[NSData alloc] init];
		//privateKey = [[NSData alloc] init];
		ccrMap = [[NSDictionary alloc] initWithObjectsAndKeys:@"ALLERGY", @"Alerts", @"CONDITION", @"Problems", @"IMMUNIZATION", @"Immunizations", 
				@"MEDICATION", @"Medications", @"PROCEDURE", @"Procedures", @"LABTEST", @"Results", @"PAYER", @"Payers", 
				@"DEMOGRAPHICS:VitalSigns", @"VitalSigns", @"HEALTHCAREPROVIDER", @"HealthCareProviders", 
				@"DEMOGRAPHICS", @"SocialHistory", nil];
		// dataLink = @"mantle.dyndns.org/hospital"; // default
		dataLink = [UserSettings getActiveHospitalURL];
		ccrEntries = [[NSMutableDictionary alloc] init];
	}
	
	return self;
}

-(id) initWithHost:(NSString *) host
{
	// set super-class init to ourself
	if(self = [super init]) {
		// do initialization of data items
		//xmlData = [[NSData alloc] init];
		privateKey = [[NSData alloc] init];
		if(host) {
			dataLink = host;
		}
	}
	
	return self;
	
}

// if user authenticates successfully, create links
// ONLY FOR TESTING PURPOSES : DO NOT USE AND NOT SAFE, I REPEAT, DO NOT USE!!!
-(BOOL) authenticateWithHTTP:(NSString *) user andPass: (NSString *) pass
{
	NSString *urlAuth = [NSString stringWithFormat:@"http://%@:%@@%@/%@/authTok", user, pass, dataLink, user];
	// NSLog(@"Download XML => '%@'", urlAuth);		
	NSURL *service = [[NSURL alloc] initWithString:urlAuth];
	BOOL result = NO;
	//NSURLRequest *theReq = [[NSURLRequest alloc] initWithURL:service cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
	
	//NSURLConnection *theCon = [[NSURLConnection alloc] initWithRequest:theReq delegate:self];
	
	NSData *authData = [NSData dataWithContentsOfURL:service];
	
	if(authData) {
		
		NSString *authTok = [[NSString alloc] initWithData:authData encoding:NSASCIIStringEncoding];
		NSLog(@"authTok verification => %@", authTok);
		[authTok release];
		// store user pass
		username = user;
		password = pass;
		// keep dataLink
		result = YES;
	}

	if(result == NO)
		NSLog(@"authTok wasnt found.");

	[service release];
	return result;
	
}

-(BOOL) authenticateWithHTTPS:(NSString *) user andPass: (NSString *) pass
{
	// to be done soon!
	return NO;
}

-(void) downloadXML
{
	NSString *xmlURL = [NSString stringWithFormat:@"http://%@:%@@%@/%@/full_enc_ccr.xml", username, password, dataLink, username];
	NSURL *service = [[NSURL alloc] initWithString:xmlURL];
	// NSLog(@"Download XML from => '%@'", [service absoluteURL]);

	//if(xmlData != nil) 
	//	[xmlData release];
	xmlData = [NSData dataWithContentsOfURL: service];
	
	if(xmlData) {
		NSString *xml = [[NSString alloc] initWithData:xmlData encoding:NSASCIIStringEncoding];
		// NSLog(@"XML => %@", xml);
		NSError *error = nil; 
		// NSXMLElement *ccrXML = [[[NSXMLElement alloc] initWithXMLString:str error:&error] autorelease]; 
		// if (error != nil) { ... } 
		NSXMLDocument *xmlDoc = [[NSXMLDocument alloc] initWithData:xmlData options:0 error:&error];
		
		if(error == nil) {
			//NSLog(@"XML Details => %@", [xmlDoc rootElement]);
			// sets the XML element
			[self deconstructDoc:xmlDoc];
			// TODO: consider writing encrypted xmlDoc to disk, if caching enabled?
		}
		[xml release];
		[xmlDoc release];
	}
	else {
		NSLog(@"XML file not found! Check name and try again!");
	}
}

-(void) deconstructDoc:(NSXMLDocument *) document
{
	NSXMLElement *element = [document rootElement];
	NSArray *sections = [element elementsForName:@"Body"];
	NSMutableArray *entryObjects = [[NSMutableArray alloc] init];
	
	if([sections count] == 1) {
		NSEnumerator *e = [[[sections objectAtIndex:0] children] objectEnumerator];
		NSXMLNode *n, *n1;
		//printf("Number of sections: %i\n", [[sections objectAtIndex:0] childCount]);
		
		while(n = [e nextObject]) {
			// NSLog(@"Section name => '%@'", [n name]);
			// printf("Section has number of children => %i\n", [n childCount]);
			NSString *container = [[[NSString alloc] initWithFormat:@"<%@></%@>", [n name], [n name]] autorelease];
			if([n childCount] > 0) {
				NSEnumerator *e1 = [[n children] objectEnumerator];
				while(n1 = [e1 nextObject]) {
					// NSLog(@"Sub-section entry => '%@'", [n1 name]);
					CCRObject *c = [[CCRObject alloc] init];
					//if(![[n1 name] isEqualToString:@"Provider"])
					NSXMLElement *entry = [self constructCCREntry:container withNode:n1];
					NSString *entrySection = [ccrMap objectForKey:[n name]];
					// NSLog(@"CCR section => %@", entrySection);
					// extract stuff from n1

					// TODO: Add to CCR objects and store into array
					c.item = @"Empty";
					c.ccrsection = entrySection;
					c.XmlElement = entry;
					[c initOtherXMLObjects];
					if([c isEntryEncrypted] == YES) {
						// make sure c.item is set accordingly
						// c.item =  @"[!ENCRYPTED ENTRY!]"; // [c getEncryptedValue];
						c.item = ENCRYPTED_ENTRY;
					}
					[entryObjects addObject:c];
					[c release];
					[entry release];
				}
			}
			// [container release];	
		}
	}
	
	if([entryObjects count] > 0) {
		[ccrEntries setObject:entryObjects forKey:username];
		[entryObjects release];
	}
	// NSArray *a = [xmlParser findChild:element withTag:@"Condition"];
}

// TODO: Finish adding arguments to this function..
-(NSXMLElement *) constructCCREntry:(NSString *) container withNode:(NSXMLNode *) tree
{
	NSString *str = @"<ContinuityOfCareRecord xmlns='urn:astm-org:CCR'><CCRDocumentObjectID>AjdkfeLAA</CCRDocumentObjectID></ContinuityOfCareRecord>";
	
	NSError *error = nil;
	NSXMLElement *ccrXML = [[NSXMLElement alloc] initWithXMLString:str error:&error]; 
	NSXMLElement *entry  = [[[NSXMLElement alloc] initWithXMLString:container error:&error] autorelease];
				// [NSXMLNode elementWithName:container];
	NSXMLElement *body   = // [[[NSXMLElement alloc] initWithXMLString:@"<Body></Body>" error:&error] autorelease];
				[NSXMLNode elementWithName:@"Body"];
	// build-up ccr node structure CCR => Body => Category => Entry
	[entry addChild:tree];
	[body addChild:(NSXMLNode *) entry];
	// [entry release];
	[ccrXML addChild:(NSXMLNode *) body];
	// NSLog(@"After re-Add: XML => %@", ccrXML);
	// [body release];
	// [ccrXML release];
	return ccrXML;
}

//-(void) downloadPrivateKey {  }

-(void) dealloc
{
	[xmlData release];
	[privateKey release];
	[ccrMap release];
	[ccrEntries release];
	[super dealloc];
}

@end
